import 'package:enjoy_plus_community/components/loading.dart';
import 'package:enjoy_plus_community/routes/index.dart';
import 'package:enjoy_plus_community/utils/eventbus.dart';
import 'package:enjoy_plus_community/utils/http.dart';
import 'package:enjoy_plus_community/utils/toast.dart';
import 'package:flutter/material.dart';

import 'components/house_item.dart';

class HouseList extends StatefulWidget {
  const HouseList({super.key});

  @override
  State<HouseList> createState() => _HouseListState();
}

class _HouseListState extends State<HouseList> {
  List _houseList = [];
  bool _isLoading = true;

  void getHouseList() async {
    setState(() {
      _isLoading = true;
    });
    final res = await http.get('/house');
    if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
    ToastUtil.showSuccess('获取数据成功');
    setState(() {
      _houseList = res['data'];
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    getHouseList();
    eventBus.on<RefreshHouseList>().listen((event) {
       setState(() {
         _houseList = [];
         getHouseList();
       });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('我的房屋'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: _isLoading
          ? Loading()
          : Container(
              padding: EdgeInsets.all(10),
              constraints: BoxConstraints.expand(), // 强制填满父组件
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  ListView.separated(
                    itemBuilder: (BuildContext context, int index) {
                      return HouseItem(houseInfo: _houseList[index]);
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(
                        height: 10,
                        color: const Color.fromARGB(255, 241, 238, 238),
                      );
                    },
                    itemCount: _houseList.length,
                  ),
                  SizedBox(
                    height: 60,
                    width: MediaQuery.of(context).size.width,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pushNamed(context, AppRouter.locationList);
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [Icon(Icons.add), Text('添加房屋')],
                      ),
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}
